package com.cino.protocol;

import com.cino.common.Invocation;
import com.cino.register.LocalRegister;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.Method;

public class HttpServerHandler {

    public void handler(HttpServletRequest req, HttpServletResponse resp){
        //处理请求:接口，方法名，参数，（也就是通过这几个属性锁定一个方法）
        try {
            Invocation invocation = (Invocation) new ObjectInputStream(req.getInputStream()).readObject();
            String interfaceName = invocation.getInterfaceName();

            Class classImpl = LocalRegister.get(interfaceName);
            //通过class类获取他的方法
            Method method = classImpl.getMethod(invocation.getMethodName(), invocation.getParameterTypes());
            //再通过方法反射来执行
            String result = (String) method.invoke(classImpl.newInstance(), invocation.getParameters());
            //----⬆以上完成服务调用----

            //把结果写入resp
            IOUtils.write(result, resp.getOutputStream());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
